package com.web.wps.service.impl;


import com.web.wps.dto.*;
import com.web.wps.propertie.ApplicationProperties;
import com.web.wps.service.WpsWebService;
import com.web.wps.util.FileTypeUtil;
import com.web.wps.util.SignatureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class WpsWebServiceImpl implements WpsWebService {
    @Override
    public WpsViewUrl getViewUrl(String fileUrl, boolean isCheckToken) {
        WpsViewUrl t = new WpsViewUrl();

        String fileType = FileTypeUtil.getFileTypeByPath(fileUrl);
        // fileId使用uuid保证出现同样的文件而是最新文件,要与下面fileId一致
        String uuid = "123456543";//UUID.randomUUID().toString().replaceAll("-", "");
        String userId;
            userId = "-1";

        Map<String, String> values = new HashMap<String, String>() {
            {
                put("_w_appid", ApplicationProperties.appid);
                if (isCheckToken) {
                     put("_w_tokentype", "1");
                }
                put("_w_redirectkey", "123456");
                put("_w_userid", userId);
                put("_w_filepath", fileUrl);
                put("_w_filetype", "web");
            }
        };

        String wpsUrl = getWpsUrl(values, fileType, uuid);
        t.setToken(uuid);
        t.setExpiresIn(600);
        t.setWpsUrl(wpsUrl);
        return t;
    }

    @Override
    public String getWpsUrl(Map<String, String> values, String fileType, String fileId) {
        String keyValueStr = SignatureUtil.getKeyValueStr(values);
        String signature = SignatureUtil.getSignature(values, ApplicationProperties.appSecret);
        String fileTypeCode = FileTypeUtil.getFileTypeCode(fileType);
        return ApplicationProperties.domain + fileTypeCode + "/" + fileId + "?"
                + keyValueStr + "_w_signature=" + signature;
    }

    @Override
    public Map<String, Object>  getWebFileInfo(String filePath) {
        log.info("_w_filepath:{}", filePath);

        WpsUserDTO wpsUser;
        String userId;

            userId ="-1";
            wpsUser = new WpsUserDTO(
                    userId, "我", "read", "https://zmfiletest.oss-cn-hangzhou.aliyuncs.com/user0.png"
            );

        // 构建默认user信息


        int fileSize = FileTypeUtil.getFileSize(filePath);
        // 构建文件
        String fileId =   "123456543"; //UUID.randomUUID().toString().replaceAll("-", "");
        WpsFileDTO file = new WpsFileDTO(
                fileId, FileTypeUtil.getFileName(filePath),
                3, fileSize, userId, new Date().getTime(), filePath,
                // 默认设置为无水印，只读权限
                new WpsUserAclBO(), new WpsWatermarkBO()
        );

        return new HashMap<String, Object>() {
            {
                put("file", file);
                put("user", wpsUser);
            }
        };
    }
}
